#include <fstream>
#include "File.h"
#include "StringUtil.h"
#include "ReportError.h"

bool File::OpenRead(const std::string& filename)
{
	m_file.open(filename);

	if(m_file.is_open())
	{
		m_name = filename;
		m_currentLine = 1;

		m_file.seekg(std::ios_base::beg);
		return true;
	}

	m_file.close();
	return false;
}

std::string File::GetCurrentLineStr()
{
	return ToString(m_currentLine);
}

bool File::GetInteger(int* intResult)
{
	std::string str;
	int tempInt = 0;
	if(GetString(&str))
	{
		if(FromString(tempInt, str))
		{
			*intResult = tempInt;
			return true;
		}
	}
	return false;
}

bool File::GetFloat(float* floatResult)
{
	std::string str;
	float tempFloat = 0.0f;
	if(GetString(&str))
	{
		if(FromString(tempFloat, str))
		{
			*floatResult = tempFloat;
			return true;
		}
	}
	return false;
}

bool File::GetString(std::string* stringResult)
{
 	while(true)
	{
		std::string line;

		std::getline(m_file, line);

		//check if end of file has been reached
		if(line == "FileEnd")
		{
			m_file.close();
			return false;
		}
		//check if line was read successfully
		if(!m_file.good())
		{
			m_file.close();
			return false;
		}

		//check if line is empty or has a comment
		if((line.empty()) || (line[0] == '#'))
		{
			continue;
		}
		if(line[0] == '/' && line[1] == '/')
		{
			continue;
		}


		*stringResult = line;
		++m_currentLine;
		return true;
	}
}

bool File::GetBool(bool* boolResult)
{
	std::string str;
	if(GetString(&str))
	{
		if(str == "true" ||str == "1")
		{
			*boolResult = true;
			return true;
		}

		else if(str == "false" || str == "0")
		{
			*boolResult = false;
			return true;
		}
		else
		{
			return false;
		}
	}
	return false;
}

void File::ReportFileError(std::string& msg)
{
	ReportError(msg);
}

void File::Close()
{
	m_file.close();
	m_currentLine = 0;
	m_name = "";
}

File::~File()
{
	if(m_file.is_open())
	{
		m_file.close();
	}
}
